package com.twt.survey2025springlogin.controller;

import cn.hutool.core.convert.ConverterRegistry;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.twt.survey2025springlogin.pojo.Questionnaire;
import com.twt.survey2025springlogin.pojo.QuestionnaireDTO;
import com.twt.survey2025springlogin.pojo.SignIn;
import com.twt.survey2025springlogin.pojo.User;
import com.twt.survey2025springlogin.service.QuestionnaireService;
import com.twt.survey2025springlogin.service.UserService;
import com.twt.survey2025springlogin.utils.JwtUtil;
import com.twt.survey2025springlogin.utils.response.ResultBody;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class QuestionnaireController {

    @Resource
    QuestionnaireService questionnaireService;

    @Resource
    UserService userService;

    @Resource
    JwtUtil jwtUtil;

    @PostMapping("/survey")
    public ResultBody addQuestionnaire (@RequestBody QuestionnaireDTO questionnaireDTO,
                                        @RequestHeader(JwtUtil.TOKEN_HEADER) String token){

        String uid = (String) jwtUtil.getPayload(token).get("uid");
        User user = userService.getById(uid);
        if (user.getQuestionnaireId() != null) {
            return ResultBody.error("您已经填写过问卷", null);
        }

        Questionnaire questionnaire = new Questionnaire(questionnaireDTO);
        questionnaireService.save(questionnaire);
        Integer id = questionnaire.getId();

        user.setQuestionnaireId(id);
        userService.updateById(user);

        return ResultBody.success("填写成功！", null);

    }


    @PostMapping("/signin")
    public ResultBody login (@RequestBody SignIn signIn) {
        String account = signIn.getAccount();
        String password = signIn.getPassword();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("account", account);
        paramMap.put("password", password);

        HttpRequest loginRequest = HttpRequest.post("https://api.twt.edu.cn/api/auth/common")
                .header("domain", "weipeiyang.twt.edu.cn")
                .header("ticket", "YmFuYW5hLjM3YjU5MDA2M2Q1OTM3MTY0MDVhMmM1YTM4MmIxMTMwYjI4YmY4YTc=")
                .header("Cookie", "JSESSIONID=824387D685F213C214C3E1A67F68DF64")
                .form(paramMap);

        JSONObject jsonBody = JSONUtil.parseObj(loginRequest.execute().body(), JSONConfig.create().isIgnoreNullValue());

        ResultBody demo = new ResultBody();
        demo.setCode(String.valueOf(jsonBody.getInt("error_code")));
        demo.setMessage(jsonBody.getStr("message"));
        demo.setResult(jsonBody.get("result"));
        User user = new User();
        if (Objects.equals(demo.getMessage(), "成功")){
            ConverterRegistry converterRegistry = ConverterRegistry.getInstance();
            JSONObject tmp = JSONUtil.parseObj(jsonBody.get("result"));
            String uid = tmp.getStr("userNumber");
            String name = tmp.getStr("realname");
            tmp.remove("userNumber");
            tmp.remove("realname");
            tmp.putOpt("uid", uid);
            tmp.putOpt("name", name);
            user = converterRegistry.convert(User.class, tmp);
            if (userService.getById(user.getUid())==null){
                userService.save(user);
            }
        }else {
            return demo;
        }
        JSONObject r = JSONUtil.parseObj(user);
        String token = jwtUtil.generateToken(user);
        Date expirationDate = jwtUtil.getPayload(token).getExpiration();
        JwtUtil.tokenMap.put(token, expirationDate);
        r.putOpt("token", token);
        return ResultBody.success("success", r);
    }

}
